﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Documents;

namespace 雷赛板卡上位机.Converter
{
    public class EnumToListCoverter : IValueConverter
    {
        private List<string> _values = new List<string>();
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var data = (Enum)value;
            List<string> list = new List<string>();

            foreach (Enum item in Enum.GetValues(data.GetType()))
            {
                FieldInfo fieldInfo = item.GetType().GetField(item.ToString());
                object[] attribArray = fieldInfo.GetCustomAttributes(false);
                DescriptionAttribute attrib = attribArray[0] as DescriptionAttribute;
                list.Add(attrib.Description);
                _values.Add(attrib.Description);
            }
            return list.ToArray();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType is null) return Binding.DoNothing;
            Enum? ret = default(Enum);
            if (value == null)
            {
                ret = Activator.CreateInstance(targetType) as Enum;
            }
            else
            {
                foreach (var item in Enum.GetValues(targetType))
                {
                    FieldInfo fieldInfo = item.GetType().GetField(item.ToString());
                    object[] attribArray = fieldInfo.GetCustomAttributes(false);
                    DescriptionAttribute attrib = attribArray[0] as DescriptionAttribute;
                    if (attrib.Description == value.ToString())
                    {
                        ret = item as Enum;
                    }
                }
            }
            return ret;

        }
    }
}
